package org.company.management.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import org.company.management.utilities.Strings;
import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

/**
 * @author Paner
 *
 */
public class FileController
{
	/*
	 * User select file path
	 */
	private static String _selectedFilePath;
	
	/*
	 * User select photo
	 */
	public static void openFile()
	{
		Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
		FileDialog fd = new FileDialog(shell, SWT.OPEN);
        fd.setText(Strings.opens);
        fd.setFilterPath(Strings.C);
        String[] filterExt = { Strings.jpg };
        fd.setFilterExtensions(filterExt);
        _selectedFilePath = fd.open();

	}
	/*
	 *  Copy photo to db
	 */
	public static String copyFile() throws IOException 
    {
		File rootDir = new File(Platform.getInstanceLocation().getURL().getFile());
		File imageFolder = new  File(rootDir + Strings.imagefolder);
		
		File selectedFile = new File(_selectedFilePath);
		File copiedFile = new File(imageFolder + Strings.backslash + selectedFile.getName());
		
        FileChannel inChannel = new FileInputStream(selectedFile).getChannel();
        FileChannel outChannel = new FileOutputStream(copiedFile).getChannel();
        try
        {
        	inChannel.transferTo(0, inChannel.size(), outChannel);
        } 
        catch (IOException e)
        {
            throw e;
        }
        finally
        {
            if (inChannel != null)
        	{
        		inChannel.close();
        	}	
            if (outChannel != null)
        	{
        		outChannel.close();
        	}
        }
        return copiedFile.getAbsolutePath();
        
    }
	/*
	 * Create the image folder in selected path john
	 */
	public static void createImageFolder()
	{
		File rootDir = new File(Platform.getInstanceLocation().getURL().getFile());
		File imageFolder = new  File(rootDir + Strings.imagefolder);
		
		boolean exists = imageFolder.exists();
		if (!exists)
		{
			imageFolder.mkdir();
		}
		
	}
	
	/* john
	 * 
	 */
	public static String getImageFolderPath()
	{
		createImageFolder();
		
		File rootDir = new File(Platform.getInstanceLocation().getURL().getFile());
		File imageFolder = new  File(rootDir + Strings.imagefolder);
		
		return imageFolder.getPath();
		
	}
	
}
